$(document).ready(function () {
    $('form').parsley();
    getAllRoles();
    dynamicBinding();
});
//获得所有角色
function getAllRoles() {
    let updateStr = "";
    let deleteStr = "";
    let assignPermissions = "";
    let columns = [
        {
            title: "序号", data: null, "render": function (data, type, row, meta) {
                return data = Number(meta.row) + Number(1);
            }
        },
        {title: "角色名字", data: "roleName"},
        {title: "角色描述", data: "roleDes"},
        {
            title: "操作", data: "id", "orderable": false, // 禁用排序
            "defaultContent": "", "render": function (data, type, row, meta) {
                if (hasDeletePermission) {
                    deleteStr = "<button data-id=" + data + "  type='button' class='btn btn-danger data-delete'>删除</button>&emsp;"
                }
                   if (hasUpdatePermission) {
                       updateStr = "<button data-id=" + data + " type='button' class='btn btn-info data-update' data-toggle='modal' data-target='#updateRoleModal'>修改</button>";
                   }
                   if (hasAssignPermissions) {
                       assignPermissions = "<button data-id=" + data + " type='button' class='btn btn-danger data-assignPermissions' data-toggle='modal' data-target='#rolePermissionModal'>分配权限</button>";
                   }
                return data = /*deleteStr + updateStr +*/ assignPermissions;
            }
        }
    ];
    let url = 'roles/getAllRoles';
    dataTableInit(url, columns);
}

//动态绑定
function dynamicBinding() {
    //为所有的delete按钮绑定delete事件
   /* deleteBind( '/roles/deleteRoles');*/
    //为所有的update按钮绑定update事件
    updateBind(  '#toUpdateRole', '/roles/updateRoles', false, false, "#updateRoleModal");
    //为所有的add按钮绑定add事件
    addBind('#toAddRole', '/roles/addRoles', false, false, "#addRolesModal");
    //为add模态框绑定消失事件-清空模态框中内容
    $('#addRolesModal').on('hidden.bs.modal', function () {
        document.getElementById("toAddRole").reset();
    });
    //为update模态框绑定消失事件-清空模态框中内容
    $('#updateRolesModal').on('hidden.bs.modal', function () {
        document.getElementById("toUpdateRole").reset();
    });

    //为所有分配权限按钮绑定分配权限事件
    $("#datatable").on('click', ".data-assignPermissions", function () {
        //打开授权模态框
        let roleId = $(this).attr('data-id');
        givePower(roleId);
        $("#submitTree").off().on('click',function () {
            let permissionIds = onCheck();
            $.ajax({
                type: "post",
                async: false,
                url: '/permission/addRolePermission',
                data: {"roleId": roleId, "permissionList": permissionIds},
                dataType: 'json',
                success: function (result) {
                    if (result.code === 200) {
                        $("#rolePermissionModal").modal('hide');
                    } else {
                        return result;
                    }
                }
            });
        });
    });

    function givePower(roleId) {
        // ajax获取后台数据
        $.ajax({
            url: '/permission/getPermissionIdParentIdName',
            async: false,
            dataType: 'json',
            success: function (result) {
                let zNodes = result.msg;
                // 生成树结构
                treeList(zNodes,roleId);
                //调用方法  获取roleId
            },
            error: function () {
                //toast.error("查询角色树节点失败");
            }
        });
    }
    //创建树
    function treeList(roleResourceList,roleId) {
        let setting = {
            check: {
                enable: true,//复选框
                //chkDisabledInherit: tr,
                chkStyle: "checkbox",
                checkboxType: {"Y": "p", "N": "s"} //控制父选框和子选框的同步
            },
            view: {
                selectedMulti: false
            },
            data: {
                key: {
                    name: "name", //节点显示的值
                },
                simpleData: {
                    enable: true,//如果为true，可以直接把从数据库中得到的List集合自动转换为Array格式。而不必转换为json传递
                    idKey: "id",//节点的id
                    pIdKey: "parentId",//节点的父节点id
                    rootPId: ""
                }
            }
        };
        // 初始化树 //参数1：容器对象  2：tree的setting设置  3：接收后台返回值的数组
        $.fn.zTree.init($("#permissionTree"), setting, roleResourceList);
        //动态加载zTree的选中值
        $.ajax({
            type: "get",
            async: false,
            url: '/permission/getPermissionByRoleId',
            data: {"roleId": roleId},
            dataType: 'json',
            success: function (result) {
                if (result.code === 200) {
                    let permission = result.msg;
                    let treeObj = $.fn.zTree.getZTreeObj("permissionTree");//获取Tree对象
                    for (let i = 0; i < permission.length; i++) {
                        let value = permission[i].id;
                        let node = treeObj.getNodeByParam("id", value);//根据ID找到该节点
                        if (node != null) {
                            treeObj.checkNode(node);//根据该节点选中
                        }
                    }
                }
            }
        });
    }

    //获取被选中的id 值
    function onCheck() {
        //树
        let treeObj = $.fn.zTree.getZTreeObj("permissionTree");
        //选中的框的树的节点
        let nodes = treeObj.getCheckedNodes(true);
        let v = "";
        for (let i = 0; i < nodes.length; i++) {
            v += nodes[i].id + ",";
        }
        return v;
    }
/*    //授权操作
    function doSaveRole(roleId) {

    }*/
}